package com.scwatch.core.web.back;

import com.alibaba.fastjson.JSONObject;
import com.scwatch.common.orm.RowSide;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.*;
import com.scwatch.core.html.HtmlService;
import com.scwatch.core.service.GcService;
import com.scwatch.core.service.ModelService;
import com.scwatch.core.service.NodeQueryService;
import com.scwatch.core.service.OperationLogService;
import com.scwatch.core.support.Backends;
import com.scwatch.core.support.Context;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.scwatch.core.constant.Constants.*;
import static com.scwatch.core.constant.Constants.SAVE_SUCCESS;

/**
 * @author mafei
 * @Title: GcController
 * @ProjectName SCGC_CMS
 * @Description: 高层分类管理
 * @date 2018/10/1515:16
 */
@Controller
@RequestMapping("/core/gc")
public class GcController {

    private static final Logger logger = LoggerFactory
            .getLogger(GcController.class);


    @Autowired
    GcService gcService;

    @Autowired
    private OperationLogService logService;

    @Autowired
    private ModelService modelService;
    @Autowired
    private HtmlService htmlService;
    @Autowired
    private NodeQueryService nodeQuery;

    /**
     　　* @Description: 查询列表
     　　* @param [pageable, queryNodeId, request, modelMap]
     　　* @return java.lang.String
     　　* @throws
     　　* @author mafei
     　　* @date 2018/10/16 14:15
     　　*/
    @RequestMapping("list.do")
    @RequiresRoles("super")
    @RequiresPermissions(value = {
            "core:gc:list",
            "core:gc:list01"
    },logical = Logical.OR)
    public String list(
            @PageableDefault(sort = {"priority", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
            Integer queryNodeId,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        Integer siteId = Context.getCurrentSiteId();
        Page<GaoCeng> pagedList = gcService.findAll(params, pageable);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        return "core/gaoceng/gc_list";
    }
    /**
     　　* @Description: 新增高层人物
     　　* @param [id, modelMap]
     　　* @return java.lang.String
     　　* @throws
     　　* @author mafei
     　　* @date 2018/10/16 14:15
     　　*/
    @RequestMapping("create.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:gc:create")
    public String create(Integer id, org.springframework.ui.Model modelMap) {
        if (id != null) {
            GaoCeng bean = gcService.getById(id);
            modelMap.addAttribute("bean", bean);
        }
        modelMap.addAttribute(OPRT, CREATE);
        return "core/gaoceng/gc_form";
    }
    /**
     　　* @Description:保存高层人物
     　　* @param [id, modelMap]
     　　* @return java.lang.String
     　　* @throws
     　　* @author mafei
     　　* @date 2018/10/16 14:15
     　　*/
    @RequestMapping("save.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:gc:save")
    public String save(GaoCeng bean, String redirect,Integer specialId,
                       HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        bean.setCreateTime(new Date());
        gcService.save(bean,specialId);
        logService.operation("opr.gc.add", bean.getUserName(), null,
                bean.getId(), request);
        logger.info("save GaoCeng, name={}.", bean.getUserName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
            return "redirect:create.do";
        } else {
            ra.addAttribute("id",bean.getId());
            return "redirect:edit.do";
        }
    }

    /**
     　　* @Description: 编辑页面
     　　* @param [id, modelMap]
     　　* @return java.lang.String
     　　* @throws
     　　* @author mafei
     　　* @date 2018/10/16 14:15
     　　*/
    @RequestMapping("edit.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:gc:edit")
    public String edit(
            Integer id,
            @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        GaoCeng bean = gcService.getById(id);
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute(OPRT, EDIT);
        return "core/gaoceng/gc_form";
    }

    /**
     　　* @Description: 修改高层人物
     　　* @param [id, modelMap]
     　　* @return java.lang.String
     　　* @throws
     　　* @author mafei
     　　* @date 2018/10/16 14:15
     　　*/
    @RequestMapping("update.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:gc:update")
    public String update(@ModelAttribute("bean") GaoCeng bean,Integer specialId, String redirect, HttpServletRequest request,
                         RedirectAttributes ra) {
        bean.setCreateTime(new Date());
        gcService.update(bean,specialId);
        logService.operation("opr.gc.edit", bean.getUserName(), null,
                bean.getId(), request);
        logger.info("update GaoCeng, name={}.", bean.getUserName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            return "redirect:edit.do";
        }
    }

    /**
     　　* @Description: 删除高层人物
     　　* @param [id, modelMap]
     　　* @return java.lang.String
     　　* @throws
     　　* @author mafei
     　　* @date 2018/10/16 14:15
     　　*/
    @RequestMapping("delete.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:gc:delete")
    public String delete(Integer[] ids, HttpServletRequest request,
                         RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        GaoCeng[] beans = gcService.delete(ids);
        for (GaoCeng bean : beans) {
            logService.operation("opr.gc.delete", bean.getUserName(),
                    null, bean.getId(), request);
            logger.info("delete GaoCeng, name={}.", bean.getUserName());
        }
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:list.do";
    }

    /**
     　　* @Description: 生成数据
     　　* @param [id, modelMap]
     　　* @return java.lang.String
     　　* @throws
     　　* @author mafei
     　　* @date 2018/10/16 14:15
     　　*/
    @RequestMapping("generation.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:gc:generation")
    public String generation(Integer nodeId, org.springframework.ui.Model modelMap,RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer[] nodeIds=getNodeIdsByFlag(Constants.MODEL_FLAG_GC,siteId);
        if(nodeIds!=null && nodeIds.length>0){
            htmlService.makeNode(nodeIds[0]);
        }
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        return "redirect:list.do";
    }

    private Integer[] getNodeIdsByFlag(String modelFlag,Integer siteId) {
        Integer [] nodeIds=null;
        Map<String,String[]> paramMap=new HashMap<String,String[]>();
        paramMap.put("EQ_flag",new String[]{modelFlag});
        List<Model> models=modelService.findList(siteId,null,paramMap,null);

        paramMap=new HashMap<String,String[]>();
        String[] idsStr;
        if(models!=null && models.size()>0){
            idsStr=new String[models.size()];
            for(int i=0;i<models.size();i++){
                idsStr[i]=models.get(i).getId().toString();
            }
            paramMap.put("EQ_nodeModel.id",idsStr);
        }
        Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node>  currentNodeList=nodeQuery.findList(siteId,null,
                null,null,true,
                paramMap, paramSort);
        if(currentNodeList!=null){
            nodeIds=new Integer[currentNodeList.size()];
            for(int i=0;i<currentNodeList.size();i++){
                nodeIds[i]=(currentNodeList.get(i).getId());
            }
        }
        return  nodeIds;
    }

      /**
      　　* @Description: TODO
      　　* @param 设置优先级
      　　* @return 
      　　* @throws
      　　* @author mafei
      　　* @date 2018/10/19 9:48 
      　　*/
    @RequestMapping("updatePriority.do")
    @ResponseBody
    public String updatePriority(Integer priority,Integer infoId,
                                 HttpServletRequest request) {
        String msg="success";
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        String ip = Servlets.getRemoteAddr(request);
        if(infoId!=null && priority!=null){
            gcService.updateOrder(priority,infoId);
            logService.operation("栏目管理.设置优先级","优先级为："+priority.toString(),null,infoId, ip, user.getId(), site.getId());
            logger.info("updatePriority,id={},priority={}.",infoId,priority);
        }
        JSONObject json = new JSONObject();
        JSONObject jsons = new JSONObject();
        jsons.put("msg",msg);
        return jsons.toJSONString();
    }
}
